package cn.gov.cus.rmftquartz.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author wxming.
 * @date 2018/2/9.
 */
@Configuration
@MapperScan(basePackages = H2000DataSourceNoCamelConfig.PACKAGE,sqlSessionTemplateRef = "h2000NoCamelSqlSessionTemplate")
public class H2000DataSourceNoCamelConfig {
    static final String PACKAGE ="cn.gov.cus.rmftquartz.mappers.h2000nocamel";

    @Value("${datasource.oracle.h2000.url}")
    private String url;
    @Value("${datasource.oracle.h2000.username}")
    private String user;
    @Value("${datasource.oracle.h2000.password}")
    private String password;
    @Value("${datasource.oracle.h2000.driver-class-name}")
    private String driverClassName;
    @Value("${datasource.oracle.h2000.maxPoolSize}")
    private Integer maxPoolSize;

    @Bean(name = "h2000DataSourceNoCamel")
    @Autowired
    public DataSource h2000DataSourceNoCamel(Environment env){
        AtomikosDataSourceBean atomikosDataSource = new AtomikosDataSourceBean();
        Properties prop = OracleDataSourceConfig.getDataSourceProperties(env,"datasource.oracle.h2000.");
        atomikosDataSource.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        atomikosDataSource.setUniqueResourceName("h2000NoCamelDB");
        //因为大量多线程跑数据，限制了数据库的连接池最大为5,配置里配了5。
        atomikosDataSource.setMaxPoolSize(maxPoolSize);
        atomikosDataSource.setXaProperties(prop);
        return atomikosDataSource;
    }

    @Bean(name = "h2000SqlSessionFactoryNoCamel")
    public SqlSessionFactory h2000SqlSessionFactoryNoCamel(@Qualifier("h2000DataSourceNoCamel") DataSource h2000DataSourceNoCamel) throws Exception{
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        config.setCallSettersOnNulls(true);
        sessionFactoryBean.setConfiguration(config);
        sessionFactoryBean.setDataSource(h2000DataSourceNoCamel);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "h2000NoCamelSqlSessionTemplate")
    public SqlSessionTemplate mydbSqlSessionTemplate(@Qualifier("h2000SqlSessionFactoryNoCamel")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
